import { START_LOCATION } from 'vue-router'
import useAppStore from '@/store/app'
import { AuthRouteWhites } from './config'
import ls from '@/lib/ls'
import versionTood from '@/lib/versionUpdate'

// 路由 - 登录认证中间件
export const Auth = function(nextFn) {
    return function(to, from, next) {
        if (from===START_LOCATION) {
            const appStore = useAppStore()
            appStore.Start(to)
        }
        const token = ls.get('TOKEN')
        // 不在白名单并且token不存在
        if (!AuthRouteWhites.includes(to.path) && !token) {
            next(`/login?redirect=${to.path}`)
            return
        }
        nextFn(to, from, next)
    }
}

// 默认导航守卫
export const Default = function() {
    return function(to, from, next) {
        // document.title = '服务员点单系统'
        document.title = to.meta.title
        // 同路径不操作
        if (to.fullPath === from.fullPath && from.fullPath != '/') {
            return
        }
        // 认证白名单
        if (AuthRouteWhites.includes(to.path)) {
            //普通跳转
            return next()
        }
        versionTood.isNewVersion();  // 检测版本更新
        // document.title = to.meta.title
        next()
    }
}

export default {
    Auth,
    Default,
}